//
//  MyMoreCompetionViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/16.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MyMoreCompetionViewController.h"
#import "NOContentView.h"
#import "MyCompetionUPProducetCell.h"
#import "QQAndWechatShareView.h"
#import "WXApi.h"
#import "UMSocialQQHandler.h"
#import "AppDelegate.h"
#import "CompetionAllPersonProducetViewController.h"
#import "MatchListModel.h"
#import "RecordListModel.h"
@interface MyMoreCompetionViewController ()<UITableViewDelegate,UITableViewDataSource>{
     AppDelegate *appdelegate;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)QQAndWechatShareView *shareView;
@end

@implementation MyMoreCompetionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableViewUI];
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    [self.dataArray removeAllObjects];
    [self getDataInformationWithShowCurrentpage:@"1"];
    [self createTableViewUI];
}
-(void)createTableViewUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 104) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    UIView *view = [[UIView alloc] init];
    self.tableView.tableFooterView = view;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MyCompetionUPProducetCell class] forCellReuseIdentifier:@"MyCompetionUPProducetCell"];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
        // Fallback on earlier versions
    }
}
#pragma mark -tableview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCompetionUPProducetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCompetionUPProducetCell"];
    cell.produceBlock = ^(NSString *productId) {
        self.pushBlock(productId);
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    cell.shareQQAndWechatBlock = ^(NSString *productId) {
        [self showShareUIWithId:productId];
    };
//    cell.model = self.dataArray[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return scaleTopAndBottom(200.f);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    MatchListModel *model = self.dataArray[indexPath.row];
    //    SignUpViewController *signupVc = [[SignUpViewController alloc] init];
    //    signupVc.matchID = model.Id;
    //    signupVc.matchStarttime = model.matchStartTime;
    //    [self.navigationController pushViewController:signupVc animated:YES];
}
-(void)showShareUIWithId:(NSString *)matchId{
    UIView *backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    backView.alpha = 0.5f;
    backView.backgroundColor = [UIColor blackColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removebackView:)];
    [backView addGestureRecognizer:tap];
    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    _shareView = [[QQAndWechatShareView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, scaleTopAndBottom(94))];
    [_shareView.QQBtn addTarget:self action:@selector(QQShare:) forControlEvents:UIControlEventTouchUpInside];
    _shareView.QQBtn.tag = 100101 + [matchId integerValue];
    _shareView.WechatBtn.tag = 100102 + [matchId integerValue];
    [_shareView.WechatBtn addTarget:self action:@selector(WechatShare:) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:_shareView];
    [UIView animateWithDuration:0.1 animations:^{
        _shareView.frame = CGRectMake(0,HEIGHT - scaleTopAndBottom(94), WIDTH, scaleTopAndBottom(94));
    }];
}
-(void)WechatShare:(UIButton *)btn{
    /** 标题
     * @note 长度不能超过512字节
     */
    // @property (nonatomic, retain) NSString *title;
    /** 描述内容
     * @note 长度不能超过1K
     */
    //@property (nonatomic, retain) NSString *description;
    /** 缩略图数据
     * @note 大小不能超过32K
     */
    //  @property (nonatomic, retain) NSData   *thumbData;
    /**
     * @note 长度不能超过64字节
     */
    // @property (nonatomic, retain) NSString *mediaTagName;
    /**
     * 多媒体数据对象，可以为WXImageObject，WXMusicObject，WXVideoObject，WXWebpageObject等。
     */
    // @property (nonatomic, retain) id        mediaObject;
    
    /*! @brief 设置消息缩略图的方法
     *
     * @param image 缩略图
     * @note 大小不能超过32K
     */
    //- (void) setThumbImage:(UIImage *)image;
    //缩略图
    
    UIImage *image = [UIImage imageNamed:@"LOGO4"];
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"拼才艺，发现自己，展现自我";
    message.description = @"加入趣味赛事，增长经验值，让孩子在参与中获得自信与快乐";
    //png图片压缩成data的方法，如果是jpg就要用 UIImageJPEGRepresentation
    message.thumbData = UIImagePNGRepresentation(image);
    [message setThumbImage:image];
    WXWebpageObject *ext = [WXWebpageObject object];
    NSString *matchId = [NSString stringWithFormat:@"%ld",btn.tag - 100102];
    ext.webpageUrl = [NSString stringWithFormat:@"%@/h5/m_share?id=%@",ServerIp,matchId];
    message.mediaObject = ext;
    message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";
    
    SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init];
    sentMsg.message = message;
    sentMsg.bText = NO;
    sentMsg.scene =  WXSceneSession;
    //    //选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)
    //    if (isPengyouquan) {
    //        sentMsg.scene = WXSceneTimeline;  //分享到朋友圈
    //    }else{
    //        sentMsg.scene =  WXSceneSession;  //分享到会话。
    //    }
    
    //如果我们想要监听是否成功分享，我们就要去appdelegate里面 找到他的回调方法
    // -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法，然后把分享的结果返回回来。
    appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //添加对appdelgate的微信分享的代理
    //    appdelegate.wxDelegate = self;
    BOOL isSuccess = [WXApi sendReq:sentMsg];
}
-(void)QQShare:(UIButton *)btn{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"http://www.tj698.com/resource/img/logo.png";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"拼才艺，发现自己，展现自我" descr:@"加入趣味赛事，增长经验值，让孩子在参与中获得自信与快乐" thumImage: thumbURL];
    //设置网页地址
    NSString *matchId = [NSString stringWithFormat:@"%ld",btn.tag - 100101];
    shareObject.webpageUrl = [NSString stringWithFormat:@"%@/h5/m_share?id=%@",ServerIp,matchId];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}
-(void)removebackView:(UITapGestureRecognizer *)tap{
    
    [UIView animateWithDuration:0.1 animations:^{
        UIView *view = tap.view;
        [view removeFromSuperview];
        [_shareView removeFromSuperview];
    }];
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(void)getDataInformationWithShowCurrentpage:(NSString *)showpage{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/matchRecordApp/attendMatchList";
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *param = @{@"sessionId":sessionId,@"currentPage":@"1",@"showCount":showpage};
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArra = jsonDic[@"list"];
        for (NSDictionary *dict in dataArra) {
            RecordListModel *model = [RecordListModel modelWithDictionary:dict];
            [self.dataArray addObject:model];
        }
        
        if (self.dataArray.count == 0) {
            NOContentView *noconteView = [NOContentView initWithImage:@"订单无数据" AndWithTitile:@"空空如也 赶快参赛吧"];
            noconteView.frame = self.view.bounds;
            [self.view addSubview:noconteView];
        }else{
            NSLog(@"数组%@",self.dataArray);
            [self.tableView reloadData];
        }
        
        NSLog(@"%@",jsonDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败%@",error);
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
